<?php
namespace app\Capital\admin;
use app\admin\controller\Admin;
use app\common\builder\ZBuilder;
use think\Model;
use think\Db;
use app\Capital\model\capital as CapitalModel;
use app\Capital\model\account;
class Creditlimit extends Admin{
        public function index()
        {
            //超期临时额度作废
            $data=Db::name("member")->where('temporary_endtime' ,'<',time() )->update(['temporary_creditlimit'=>0,'']);
            $map=$this->getMap();
            $id=input('id');
            if($id){
                $map['id']=$id;
            }
            $MemberList=Db::name("member")->where($map)->order('id desc')->paginate(10);
            //分页数据
            $page=$MemberList->render();
            return ZBuilder::make('table')
                ->hideCheckbox()
                ->setPageTitle('会员信用额度')
                ->setSearch(['id'=>'ID','company'=>'会员名称','mobile'=>'手机号','name'=>'联系人'])
                ->addColumns([
                    ['company','会员名称'],
                    ['name','联系人'],
                    ['mobile','手机号码'],
                    ['balance','会员余额'],
                    ['creditlimit','固定额度','callback','getPrice'],
                    ['account_period','固定额度账期'],
                    ['temporary_creditlimit','临时信用额度','callback','getPrice'],
                    ['right_button', '操作', 'btn']

                ])
                ->addTimeFilter('createtime')
                ->addRightButton('custom', ['title' => '新增额度', 'icon' => 'fa fa-fw fa-plus','href'=>url('creditlimit_add',['id'=>'__id__'])])// 批量添加右侧按钮
                ->addRightButton('custom', ['title' => '编辑额度', 'icon' => 'fa fa-wrench','href'=>url('creditlimit_edit',['id'=>'__id__'])])// 批量添加右侧按钮
                ->addRightButton('custom', ['title' => '额度查看', 'icon' => 'fa fa-fw fa-eye','href'=>url('creditlimit_list',['id'=>'__id__'])])// 批量添加右侧按钮
                ->setRowList($MemberList)
                ->setPages($page)
                ->fetch();
        }

        //会员额度列表
        public function creditlimit_list(){
            $map=$this->getMap();
            $id=input('id');
            if($id){
                $map['memberid']=$id;
            }
            $status=input('status');
            if(99==$status){
                $map['creditlimit_status']=0;
            }
            $map['creditlimit_type']=['in','(0,2)'];
            $list_tab = [
                'tab1' => ['title' => '会员固定额度列表', 'url' => url('creditlimit_list', ['id' => $id])],
                'tab2' => ['title' => '会员临时额度列表', 'url' => url('temporary_creditlimit_list', ['id' => $id])],
            ];
            $data=Db::name("member_creditlimit")->where($map)->order('id desc')->select();
            return ZBuilder::make('table')
                ->setTabNav($list_tab,  'tab1')
                ->hideCheckbox()
                ->setSearch(['id'=>'ID','no'=>'单据号','memberid'=>'会员ID'])
                ->addColumns([
                    ['no','单据号'],
                    ['creditlimit','额度','callback','getPrice'],
                    ['account_period','固定额度账期'],
                    ['createtime','创建时间','datetime'],
                ])
                ->addColumn('creditlimit_status', '状态', 'status', '', [0 => '待审核', 1 => '已审核', 2 => '已作废'])
                ->addColumn('right_button', '操作', 'btn')
                ->addTopButton('add', ['title' => '新增', 'table' => '','href'=>url('creditlimit_add',['id'=>$id])])
                ->addTopButton('custom', ['title' => '待审核','icon' => 'fa fa-fw fa-cogs', 'href' =>url('creditlimit_list',['id'=>$id,'status'=>99])])
                ->addRightButton('custom', ['title' => '单据审核', 'icon' => 'fa fa-fw fa-key','href'=>url('creditlimit_auditing',['id'=>'__id__'])])// 批量添加右侧按钮
                ->addTimeFilter('createtime')
                ->setRowList($data)
                ->fetch();
        }
        //会员临时额度列表

        public function temporary_creditlimit_list(){
            $map=$this->getMap();
            $id=input('id');
            if($id){
                $map['memberid']=$id;
            }
            $status=input('status');
            if(99==$status){
                $map['creditlimit_status']=0;
            }
            $map['creditlimit_type']=1;
            $list_tab = [
                'tab1' => ['title' => '会员固定额度列表', 'url' => url('creditlimit_list', ['id' => $id])],
                'tab2' => ['title' => '会员临时额度列表', 'url' => url('temporary_creditlimit_list', ['id' => $id])],
            ];
            $data=Db::name("member_creditlimit")->where($map)->order('id desc')->select();
            return ZBuilder::make('table')
                ->setTabNav($list_tab,  'tab2')
                ->hideCheckbox()
                ->setSearch(['id'=>'单据ID','no'=>'单据号'])
                ->addColumns([
                    ['no','单据号'],
                    ['creditlimit','临时额度','callback','getPrice'],
                    ['temporary_time','开始日期','date'],
                    ['temporary_endtime','结束日期','date'],
                    ['createtime','创建时间','datetime'],
                ])
                ->addColumn('creditlimit_status', '状态', 'status', '', [0 => '待审核', 1 => '已审核', 2 => '已作废'])
                ->addColumn('right_button', '操作', 'btn')
                ->addTopButton('add', ['title' => '新增', 'table' => '','href'=>url('creditlimit_add',['id'=>$id])])
                ->addTopButton('custom', ['title' => '待审核','icon' => 'fa fa-fw fa-cogs', 'href' =>url('temporary_creditlimit_list',['id'=>$id,'status'=>99])])
                ->addRightButton('custom', ['title' => '单据审核', 'icon' => 'fa fa-fw fa-key','href'=>url('creditlimit_auditing',['id'=>'__id__'])])// 批量添加右侧按钮
                ->addTimeFilter('createtime')
                ->setRowList($data)
                ->fetch();

        }

        //信用额度单据审核
        public function creditlimit_auditing(){
            $id=input('id');
            if($id) {
                $re = Db::name("member_creditlimit")->where('id', $id)->find();
                if ($re) {
                    Db::startTrans();
                    try {
                        $result = Db::name("member_creditlimit")->where('id', $id)->setField('creditlimit_status', 1);
                        if ($result) {
                            $member = Db::name("member")->where('id', $re['memberid'])->find();
                            switch ($re['creditlimit_type']) {
                                case 0:
                                    //固定额度增加
                                    $data['creditlimit'] = $member['creditlimit']+$re['creditlimit'];
                                    break;
                                case 1:
                                    //临时额度增加
                                    $now = time();
                                    if ($re['temporary_endtime'] > $now) {
                                        $data['temporary_creditlimit'] = $member['temporary_creditlimit'] + $re['creditlimit'];
                                    }
                                    break;
                                default:
                                    $data['account_period'] = $re['account_period'];
                                    break;
                            }
                            $creditlimit = Db::name("member")->where('id', $re['memberid'])->update($data);
                            $account = [];
                            if ($creditlimit) {
                                if (2!=$re['creditlimit_type']) {
                                    $account['memberid'] = $re['memberid'];
                                    $account['no'] = $re['no'];
                                    $account['num'] = $re['creditlimit'];
                                    if (1 == $re['creditlimit_type']){
                                        $account['type'] = 12;
                                        $account['balance']=$member['temporary_creditlimit'];
                                    }else{
                                        $account['type'] = 13;
                                        $account['balance']=$member['creditlimit'];
                                    }
                                    $member_account=account::add_member_account($account);
                                    $msg="";
                                    if ($member_account) {
                                        $msg = '单据审核成功，会员信用额度已变更，交易数据已保存';
                                    }
                                }else{
                                    $msg="单据审核成功，会员账期已变更";
                                }
                            }
                        }
                        Db::commit();
                    }catch (\Exception $e) {
                        Db::rollback();
                        $this->error('单据审核失败');
                    }
                   $this->success($msg);
                } else {
                    return $this->error('操作失败');
                }
            }else{
                $this->error("单据错误");
            }
        }



        //会员额度新增
        public function creditlimit_add(){
            $id=input('id');
            $data=CapitalModel::get_member($id);
            return ZBuilder::make('form')
                ->setPageTitle('会员信用额度')
                ->addHidden('id',$data['id'])
                ->addStatic('company', '会员名称','',$data['company'])
                ->addStatic('name', '联系人','',$data['name'])
                ->addStatic('mobile', '手机号','',$data['mobile'])
                ->addText('creditlimit', '固定额度','','','','onkeyup="if(isNaN(value))execCommand(\'undo\')" 6onafterpaste="if(isNaN(value))execCommand(\'undo\')"')
                ->addText('temporary_creditlimit', '临时信用额度','','','','onkeyup="if(isNaN(value))execCommand(\'undo\')" 6onafterpaste="if(isNaN(value))execCommand(\'undo\')"')
                ->addDaterange('temporary_time,temporary_endtime', '临时信用额度日期范围')
                ->layout(['company'=>3,'name'=>3,'mobile'=>6,'creditlimit'=>2,'account_period'=>2,'temporary_creditlimit'=>2,'temporary_time'=>4,'temporary_endtime'=>4])
                ->setUrl(url('creditlimit'))
                ->fetch();
        }

        //会员额度保存
        public function creditlimit(){
            $data=input();
            $result='';
            $creditlimit='';
            $temporary_creditlimit='';
            if($data['temporary_creditlimit'] &&!$data['creditlimit']){
                //会员额度新增
                $temporary_creditlimit['memberid']=$data['id'];
                $temporary_creditlimit['no']='LS-'.$data['id'].time();
                $temporary_creditlimit['creditlimit_type']=1;
                $temporary_creditlimit['creditlimit']=setPrice($data['temporary_creditlimit']);
                $temporary_creditlimit['temporary_time']=strtotime($data['temporary_time']);
                $temporary_creditlimit['temporary_endtime']=strtotime($data['temporary_endtime']);
                $temporary_creditlimit['createtime']=time();
                $result=Db::name('member_creditlimit')->insert($temporary_creditlimit);
            }elseif($data['creditlimit'] && !$data['temporary_creditlimit']){
                $creditlimit['memberid']=$data['id'];
                $creditlimit['no']='GD-'.$data['id'].time();
                $creditlimit['creditlimit_type']=0;
                $creditlimit['creditlimit']=setPrice($data['creditlimit']);
                $creditlimit['createtime']=time();
                $result=Db::name('member_creditlimit')->insert($creditlimit);
            }elseif($data['creditlimit'] && $data['temporary_creditlimit']){
                //同时增加固定额度和临时额度
                $creditlimit['memberid']=$data['id'];
                $creditlimit['no']='GD-'.$data['id'].time();
                $creditlimit['creditlimit']=setPrice($data['creditlimit']);
                $creditlimit['createtime']=time();
                $creditlimit['creditlimit_type']=0;
                $creditlimit_result=Db::name('member_creditlimit')->insert($creditlimit);
                $temporary_creditlimit['memberid']=$data['id'];
                $temporary_creditlimit['no']='LS-'.$data['id'].time();
                $temporary_creditlimit['creditlimit_type']=1;
                $temporary_creditlimit['creditlimit']=setPrice($data['temporary_creditlimit']);
                $temporary_creditlimit['temporary_time']=strtotime($data['temporary_time']);
                $temporary_creditlimit['temporary_endtime']=strtotime($data['temporary_endtime']);
                $temporary_creditlimit['createtime']=time();
                $temporary_creditlimit_result=Db::name('member_creditlimit')->insert($temporary_creditlimit);
            }else{
                return $this->error('新增失败');
            }
            if($result){
                return $this->success('新增成功',url('index'));
            }elseif($creditlimit && $temporary_creditlimit){
                return $this->success('新增成功',url('index'));
            }elseif($creditlimit && !$temporary_creditlimit) {
                return $this->success('固定额度新增成功，临时额度新增失败', url('index'));
            }elseif(!$creditlimit && $temporary_creditlimit){
                return $this->success('临时额度新增成功，固定额度新增失败', url('index'));
            }else{
                return $this->error('新增失败');
            }
        }

        //会员信用额度编辑

        public function creditlimit_edit(){
            $id=input('id');
            if($id){
                $data=CapitalModel::get_member($id);
              //  dump($data);exit();
                if($data){
                    $this->assign('data',$data);
                    return $this->fetch('creditlimit_edit');
                }else{
                    $this->error("会员信用额度数据错误");
                }
            }else{
                $this->error("会员额度错误");
            }

        }

        //会员信用额度、临时额度保存
        public function creditlimit_save(){
            $data=input();
         //   dump($data);exit();
            if($data) {
                Db::startTrans();
                try {
                    $member = CapitalModel::get_member($data['id']);
                    $result = '';
                    if ($data['creditlimit'] != $member['creditlimit']) {
                        //会员固定额度修改
                        $creditlimit['memberid'] = $data['id'];
                        $creditlimit['creditlimit'] = setPrice($data['creditlimit']);
                        $creditlimit['creditlimit_type'] = 0;
                        $creditlimit['no'] = 'GD-' . $data['id'] . time();
                        $creditlimit['createtime'] = time();
                        $re = Db::name('member_creditlimit')->insert($creditlimit);
                        $msg = "";
                        if ($re) {
                            //修改固定额度账期
                            if ($data['account_period'] != $member['account_period'] && $data['temporary_creditlimit'] == $member['temporary_creditlimit']) {
                                $account_period['memberid'] = $data['id'];
                                $account_period['account_period'] = $data['account_period'];
                                $account_period['creditlimit_type'] = 2;
                                $account_period['no'] = 'GD-' . $data['id'] . time();
                                $account_period['createtime'] = time();
                                $result = Db::name('member_creditlimit')->insert($account_period);
                                if ($result) {
                                    $msg = "固定额度账期修改申请已提交";
                                }
                            } elseif ($data['account_period'] == $member['account_period'] && $data['temporary_creditlimit'] != $member['temporary_creditlimit']) {
                                //会员临时额度修改
                                $temporary_creditlimit['memberid'] = $data['id'];
                                $temporary_creditlimit['creditlimit'] = setPrice($data['temporary_creditlimit'] - $member['temporary_creditlimit']);
                                $temporary_creditlimit['creditlimit_type'] = 1;
                                $temporary_creditlimit['no'] = 'LS-' . $data['id'] . time();
                                $temporary_creditlimit['createtime'] = time();
                                $temporary_creditlimit['temporary_time'] = strtotime($data['temporary_time']);
                                $temporary_creditlimit['temporary_endtime'] = strtotime($data['temporary_endtime']);
                                $result = Db::name('member_creditlimit')->insert($temporary_creditlimit);
                                if ($result) {
                                    $msg = "临时额度修改申请已提交";
                                }
                            } elseif ($data['account_period'] != $member['account_period'] && $data['temporary_creditlimit'] != $member['temporary_creditlimit']) {
                                $account_period['memberid'] = $data['id'];
                                $account_period['account_period'] = $data['account_period'];
                                $account_period['creditlimit_type'] = 2;
                                $account_period['no'] = 'GD-' . $data['id'] . time();
                                $account_period['createtime'] = time();
                                $re1 = Db::name('member_creditlimit')->insert($account_period);
                                $temporary_creditlimit['memberid'] = $data['id'];
                                $temporary_creditlimit['creditlimit'] = setPrice($data['temporary_creditlimit'] - $member['temporary_creditlimit']);
                                $temporary_creditlimit['creditlimit_type'] = 1;
                                $temporary_creditlimit['no'] = 'LS-' . $data['id'] . time();
                                $temporary_creditlimit['createtime'] = time();
                                $temporary_creditlimit['temporary_time'] = strtotime($data['temporary_time']);
                                $temporary_creditlimit['temporary_endtime'] = strtotime($data['temporary_endtime']);
                                $re2 = Db::name('member_creditlimit')->insert($temporary_creditlimit);
                                if ($re1 && $re2) {
                                    $msg = "固定额度账期和临时额度修改申请已提交";
                                }
                            }
                            if ($msg) {
                                $msg1 = "固定额度和" . $msg;
                            } else {
                                $msg1 = "固定额度";
                            }

                        }
                    } else {
                        if ($data['account_period'] != $member['account_period'] && $data['temporary_creditlimit'] == $member['temporary_creditlimit']) {
                            $account_period['memberid'] = $data['id'];
                            $account_period['account_period'] = $data['account_period'];
                            $account_period['creditlimit_type'] = 2;
                            $account_period['no'] = 'GD-' . $data['id'] . time();
                            $account_period['createtime'] = time();
                            $result = Db::name('member_creditlimit')->insert($account_period);
                            if ($result) {
                                $msg1 = "固定额度账期修改申请已提交";
                            }
                        } elseif ($data['account_period'] == $member['account_period'] && $data['temporary_creditlimit'] != $member['temporary_creditlimit']) {
                            //会员临时额度修改
                            $temporary_creditlimit['memberid'] = $data['id'];
                            $temporary_creditlimit['creditlimit'] = setPrice($data['temporary_creditlimit'] - $member['temporary_creditlimit']);
                            $temporary_creditlimit['creditlimit_type'] = 1;
                            $temporary_creditlimit['no'] = 'LS-' . $data['id'] . time();
                            $temporary_creditlimit['createtime'] = time();
                            $temporary_creditlimit['temporary_time'] = strtotime($data['temporary_time']);
                            $temporary_creditlimit['temporary_endtime'] = strtotime($data['temporary_endtime']);
                            $result = Db::name('member_creditlimit')->insert($temporary_creditlimit);
                            if ($result) {
                                $msg1 = "临时额度修改申请已提交";
                            }
                        } elseif ($data['account_period'] != $member['account_period'] && $data['temporary_creditlimit'] != $member['temporary_creditlimit']) {
                            $account_period['memberid'] = $data['id'];
                            $account_period['account_period'] = $data['account_period'];
                            $account_period['creditlimit_type'] = 2;
                            $account_period['no'] = 'GD-' . $data['id'] . time();
                            $account_period['createtime'] = time();
                            $re1 = Db::name('member_creditlimit')->insert($account_period);
                            $temporary_creditlimit['memberid'] = $data['id'];
                            $temporary_creditlimit['creditlimit'] = setPrice($data['temporary_creditlimit'] - $member['temporary_creditlimit']);
                            $temporary_creditlimit['creditlimit_type'] = 1;
                            $temporary_creditlimit['no'] = 'LS-' . $data['id'] . time();
                            $temporary_creditlimit['createtime'] = time();
                            $temporary_creditlimit['temporary_time'] = strtotime($data['temporary_time']);
                            $temporary_creditlimit['temporary_endtime'] = strtotime($data['temporary_endtime']);
                            $re2 = Db::name('member_creditlimit')->insert($temporary_creditlimit);
                            if ($re1 && $re2) {
                                $msg1 = "固定额度账期和临时额度修改申请已提交";
                            }
                        } else {
                            $msg1 = "固定额度修改申请已提交";
                        }
                    }
                    Db::commit();
                } catch (\Exception $e) {
                    Db::rollback();
                    return $this->error("修改申请失败");
                }
                return $this->success($msg1, url('creditlimit/creditlimit_list',['id'=>$data['id']]));
            }else{
                return $this->error("修改申请失败");
            }
        }
        //店铺信用额度

        public function shop_creditlimit(){
                //超期临时额度作废
                $data=Db::name("member")->where('temporary_endtime' ,'<',time() )->update(['temporary_creditlimit'=>0,'']);
                $map=$this->getMap();
                $MemberList=Db::name("member")->where($map)->order('id desc')->paginate(10);
                //分页数据
                $page=$MemberList->render();
                return ZBuilder::make('table')
                    ->hideCheckbox()
                    ->setPageTitle('店铺信用额度')
                    ->setSearch(['id'=>'ID','name'=>'店铺名称','mobile'=>'手机号'])
                    ->addColumns([
                        ['name','店铺名称'],
                        ['mobile','手机号码'],
                        ['blance','店铺余额'],
                        ['creditlimit','固定额度'],
                        ['account_period','固定额度账期'],
                        ['temporary_creditlimit','临时信用额度'],
                        ['right_button', '操作', 'btn']

                    ])
                    ->addTimeFilter('createtime')
                    ->addRightButton('custom', ['title' => '新增额度', 'icon' => 'fa fa-fw fa-plus','href'=>url('creditlimit_add',['id'=>'__id__'])])// 批量添加右侧按钮
                    ->addRightButton('custom', ['title' => '编辑额度', 'icon' => 'fa fa-wrench','href'=>url('creditlimit_eidt',['id'=>'__id__'])])// 批量添加右侧按钮
                    ->addRightButton('custom', ['title' => '额度查看', 'icon' => 'fa fa-fw fa-eye','href'=>url('creditlimit_list',['id'=>'__id__'])])// 批量添加右侧按钮
                    ->setRowList($MemberList)
                    ->setPages($page)
                    ->fetch();

            }
}